﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace myMvcBlog.Infrastructure
{
    public class PostModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var post = bindingContext.Model ?? new Post();

            var properties = bindingContext.ModelType.GetProperties();
            foreach (var prop in properties)
            {
                if (bindingContext.PropertyFilter(prop.Name))
                {
                    var result = bindingContext.ValueProvider.GetValue(prop.Name);

                    if (result != null)
                    {
                        var value = result.ConvertTo(prop.PropertyType);

                        prop.SetValue(post, value, null);
                    }
                }
            }

            return post;
        }
    }
}